package com.kk.springboot_001.controller;

import com.kk.springboot_001.pojo.dto.UserDto;
import com.kk.springboot_001.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class RegisterController {

    @Autowired
    private UserService userService;

    /**
     * 处理用户注册请求
     *
     * @param userDto  @ModelAttribute UserDto userDto会自动把表单数据绑定到UserDto对象中
     * @param redirectAttributes 重定向属性
     * @return 重定向到登录页面
     */
    @PostMapping("/register")
    public String registerUser(@ModelAttribute UserDto userDto, RedirectAttributes redirectAttributes) {
        try {
            userService.add(userDto);
            // 注册成功，重定向到登录页面并添加成功信息
            redirectAttributes.addFlashAttribute("successMessage", "注册成功，请登录！");
            return "redirect:/login";
        } catch (RuntimeException e) {
            // 捕获异常，将错误信息添加到重定向属性中
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
            // 重定向回注册页面
            return "redirect:/register";
        }
    }
}